package interfaces;

import gestores.GestorInterfaces;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import cliente.Cliente;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

public class EcranLogin extends VBox {
	
	@FXML
	private TextField user;
	@FXML
	private PasswordField pass;
	@FXML
	private Label labelErro;
	
	private String userName;
	private String password = "";
	private Stage stage;
	private Cliente cliente;
	private GestorInterfaces interfaces;

	private final String link = "http://mystock.uni.me/";
	
	public EcranLogin(Stage stage, Cliente cliente, GestorInterfaces interfaces) {
		this.stage = stage;
		this.cliente = cliente;
		this.interfaces = interfaces;
		criarJanelaLogin();
	}

	public void criarJanelaLogin() {
		FXMLLoader login = new FXMLLoader(getClass().getResource("Login.fxml"));
		login.setRoot(this);
		login.setController(this);
		try {
			login.load();
		} catch (IOException exception) {
			throw new RuntimeException(exception);
		}
		stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
		    @Override
		    public void handle(WindowEvent event) {
		    	System.exit(0);
		    }
		});
	}
	
	@FXML
	public void logInButton(ActionEvent event) {
		autenticacao();
	}

	@FXML
	public void guest(ActionEvent event) {
		//TODO Manter as duas janelas abertas e depois fechar ambas...
		interfaces.getStageActual().close();
		interfaces.ecranGuest(new Stage());
	}

	@FXML
	public void novaConta(ActionEvent event) {
		try {
			URI url = new URI(link);
			java.awt.Desktop.getDesktop().browse(url);
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
	}

	@FXML
	private void entrar(ActionEvent event) {
		stage.close();
	}

	@FXML
	public void passwordEnter(KeyEvent e) {
		KeyCode key = e.getCode();

		if (key == KeyCode.ENTER){
			autenticacao();
		}
	}
	
	private void autenticacao(){
		labelErro.setOpacity(0);
		if (user != null) {
			userName = user.getText();
			if (pass != null) {
				password = pass.getText();
			}
		}
		if (cliente.autenticacao(userName, password)) {
			stage.close();
			interfaces.ecranInicial(new Stage());
		} else {
			labelErro.setOpacity(1);
		}
	}
}
